package com.building.hcrm.ui.customcontrols;

import java.util.List;

import com.building.hcrm.R;
import com.building.hcrm.base.BaseStaffSelector;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.InStaffList;
import com.building.hcrm.common.Utils;
import com.building.hcrm.model.SysUser;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class ComStaffSelector extends BaseStaffSelector
{
	/**
	 * 团队成员(含自己)
	 */
	public static final int DISPLAY_TYPE_ALL = 0;
	/**
	 * 下属成员（不含自己）
	 */
	public static final int DISPLAY_TYPE_SUB = 1;

	public ComStaffSelector(Context context)
	{
		super(context);
		initializeView(context, null);
	}

	public ComStaffSelector(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		initializeView(context, attrs);
	}

	/**
	 * 获取可操作控件，并绑定响应操作事件监听
	 * 
	 * @param context
	 */
	private void initializeView(Context context, AttributeSet attrs)
	{
		this.setGravity(0x01);

		this.addView(View.inflate(context, R.layout.item_staff_selector, null));

		_context = context;
		_currentStaffPosition = -1;

		// 列表选取按钮
		spinner = (Spinner) findViewById(R.id.item_patient_selector_spnSelectPatient);
		spinner.setPrompt(getResources().getString(R.string.staff_selection_prompt));
		spinner.setOnItemSelectedListener(spnSelectPatient_ItemSelected);

		// 前后选取按钮
		btnPrevBed = (Button) findViewById(R.id.item_patient_selector_btnPrevBed);
		btnPrevBed.setOnClickListener(btnPrevBed_Click);
		btnNextBed = (Button) findViewById(R.id.item_patient_selector_btnNextBed);
		btnNextBed.setOnClickListener(btnNextBed_Click);

		if (null != attrs)
		{
			TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ComStaffSelector);
			boolean bEnabled = a.getBoolean(R.styleable.ComStaffSelector_selector_enabled, true);
			spinner.setEnabled(bEnabled);
			btnPrevBed.setEnabled(bEnabled);
			btnNextBed.setEnabled(bEnabled);

			a.recycle();
		}
	}

	/**
	 * 病人选取监听事件
	 */
	private AdapterView.OnItemSelectedListener spnSelectPatient_ItemSelected = new AdapterView.OnItemSelectedListener()
	{
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
		{
			_currentStaff = (SysUser) spinner.getSelectedItem();
			setOnSelectedStaff(_currentStaff);
			_currentStaffPosition = position;
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent)
		{
		}
	};

	/**
	 * 前一位病人切换监听事件
	 */
	private View.OnClickListener btnPrevBed_Click = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			if (Utils.isFastDoubleClick())
				return;
			if (_currentStaffPosition > 0)
			{
				_currentStaffPosition -= 1;
				setStaff(_currentStaffPosition);
			}
		}
	};

	/**
	 * 后一位病人切换监听事件
	 */
	private View.OnClickListener btnNextBed_Click = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			if (Utils.isFastDoubleClick())
				return;

			ShowStaffListAdapter adapter = (ShowStaffListAdapter) spinner.getAdapter();
			if (adapter == null || adapter.getCount() < 1)
				return;

			if (_currentStaffPosition < adapter.getCount() - 1)
			{
				_currentStaffPosition += 1;
				setStaff(_currentStaffPosition);
			}
		}
	};

	/**
	 * 检测是否存在
	 * 
	 * @param selectStaff
	 * @return
	 */
	public Boolean isExist(SysUser selectStaff)
	{
		if (_taskInstance == null)
		{
			return false;
		}

		List<SysUser> showStaffList = _taskInstance.getCurrentShowStaffList();

		if (showStaffList == null || showStaffList.isEmpty())
		{
			return false;
		}

		for (int i = 0; i < showStaffList.size(); i++)
		{
			SysUser inStaffInfo = showStaffList.get(i);

			if (inStaffInfo.getUserNum().equals(selectStaff.getUserNum()))
			{
				return true;
			}
		}

		return false;
	}

	/**
	 * 设定当前选取某位
	 * 
	 * @param selectStaff
	 * @return
	 */
	public Boolean setStaff(SysUser selectStaff) throws Exception
	{
		boolean reValue = false;

		if (_taskInstance == null)
			return reValue;

		// 获取当前可选取的住院病人列表
		List<SysUser> showPatientList = _taskInstance.getCurrentShowStaffList();

		if (showPatientList == null || showPatientList.isEmpty())
			return reValue;

		// 从当前可选取住院病人列表中找到所需病人，设定为当前选中病人
		for (int i = 0; i < showPatientList.size(); i++)
		{
			SysUser inPatientInfo = showPatientList.get(i);

			if (inPatientInfo.getUserNum().equals(selectStaff.getUserNum()))
			{
				_currentStaffPosition = i;
				setStaff(_currentStaffPosition);

				reValue = true;
				break;
			}
		}

		return reValue;
	}

	/**
	 * 根据序号选择
	 */
	public Boolean setStaff(int position)
	{
		spinner.setSelection(position, true);
		return true;
	}

	/**
	 * 显示适配器类
	 */
	private class ShowStaffListAdapter extends ArrayAdapter<SysUser>
	{

		private Context _context = null;
		// 显示对象
		private List<SysUser> _showStaffList = null;
		private List<SysUser> _staffWithRecordsList = null;

		public ShowStaffListAdapter(Context context, int textViewResourceId, List<SysUser> showPatientList,
				List<SysUser> patientWithRecordsList)
		{
			super(context, textViewResourceId, showPatientList);
			_context = context;
			_showStaffList = showPatientList;
			_staffWithRecordsList = patientWithRecordsList;
		}

		@Override
		public View getDropDownView(int position, View convertView, ViewGroup parent)
		{
			DropDownViewHolder holder = null;
			try
			{

				if (convertView == null)
				{
					convertView = LayoutInflater.from(_context).inflate(R.layout.item_simple_spinner_drop, parent,
							false);

					holder = new DropDownViewHolder();
					holder.txtBedLabel = (TextView) convertView.findViewById(R.id.txtBedLabel);
					holder.txtPatientName = (TextView) convertView.findViewById(R.id.txtPatientName);
					convertView.setTag(holder);
				}
				else
				{
					holder = (DropDownViewHolder) convertView.getTag();
				}
				if (_showStaffList != null)
				{
					SysUser inPatientInfo = _showStaffList.get(position);
					if (inPatientInfo != null)
					{
						holder.txtBedLabel.setText(inPatientInfo.getJobName());
						holder.txtPatientName.setText(inPatientInfo.getUserName());

						if (_staffWithRecordsList != null && _staffWithRecordsList.size() > 0)
						{

							if (_staffWithRecordsList.contains(inPatientInfo))
							{
								holder.txtBedLabel.setTextColor(Color.RED);
								holder.txtPatientName.setTextColor(Color.RED);
							}
							else
							{
								holder.txtBedLabel.setTextColor(Color.BLACK);
								holder.txtPatientName.setTextColor(Color.BLACK);
							}
						}
					}
				}
			}
			catch (Exception e)
			{
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return convertView;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			SelectItemViewHolder holder = null;
			try
			{
				if (convertView == null)
				{
					convertView = LayoutInflater.from(_context).inflate(R.layout.item_simple_spinner_selectitem,
							parent, false);

					holder = new SelectItemViewHolder();
					holder.txtContent = (TextView) convertView.findViewById(android.R.id.text1);

					convertView.setTag(holder);
				}
				else
				{
					holder = (SelectItemViewHolder) convertView.getTag();
				}

				SysUser inPatientInfo = _showStaffList.get(position);
				if (inPatientInfo != null)
				{
					String showText = String.format("%s \t%s", inPatientInfo.getJobName(), inPatientInfo.getUserName());
					holder.txtContent.setText(showText);
				}
			}
			catch (Exception e)
			{
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}

			return convertView;
		}

		private class SelectItemViewHolder
		{
			TextView txtContent;
		}

		private class DropDownViewHolder
		{
			TextView txtBedLabel;
			TextView txtPatientName;
		}
	}

	/**
	 * 异步操作任务
	 */
	private class ShowStaffListTask extends AsyncTask<Integer, String, List<SysUser>>
	{
		private ProgressDialog pd;
		private List<SysUser> _showStaffList;
		private List<SysUser> _staffWithRecordsList;
		private int _showType;
		private SysUser _selectStaff;

		public ShowStaffListTask(int showType)
		{
			_showType = showType;
			_selectStaff = null;
		}

		public ShowStaffListTask(int showType, SysUser selectPatient)
		{
			_showType = showType;
			_selectStaff = selectPatient;
		}

		public List<SysUser> getCurrentShowStaffList()
		{
			return _showStaffList;
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			if ((_showType == DISPLAY_TYPE_ALL
					&& (null == InStaffList.getInstance(_context).getList() || 0 == InStaffList.getInstance(_context)
							.getList().size())) 
				||(_showType == DISPLAY_TYPE_SUB
						&& null == InStaffList.getInstance(_context).getSubList()))
			{
				pd = new ProgressDialog(_context);
				pd.setMessage("加载员工列表...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			}
			if (_showStaffList != null)
			{
				_showStaffList.clear();
			}

			if (_staffWithRecordsList != null)
			{
				_staffWithRecordsList.clear();
			}
		}

		@Override
		protected List<SysUser> doInBackground(Integer... params)
		{
			try
			{
				_showStaffList = getStaffList(_showType);
				_staffWithRecordsList = null;
			}
			catch (Exception e)
			{
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}

			return null;
		}

		@Override
		protected void onPostExecute(List<SysUser> result)
		{
			super.onPostExecute(result);
			if (null != pd && pd.isShowing())
				pd.cancel();
			try
			{
				if (_showStaffList != null && _showStaffList.size() > 0)
				{
					ShowStaffListAdapter adapter = new ShowStaffListAdapter(_context, 0, _showStaffList,
							_staffWithRecordsList);
					spinner.setAdapter(adapter);

					// 设置选取控件可用
					spinner.setEnabled(true);
					btnNextBed.setEnabled(true);
					btnPrevBed.setEnabled(true);
				}
				else
				{
					// 设置选取控件不可用
					spinner.setEnabled(false);
					btnNextBed.setEnabled(false);
					btnPrevBed.setEnabled(false);
				}

				if (_selectStaff != null)
				{
					setStaff(_selectStaff);
				}
			}
			catch (Exception e)
			{
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}
	}

	private List<SysUser> getStaffList(int showType) throws Exception
	{
		if (showType == DISPLAY_TYPE_SUB)
		{
			return InStaffList.getInstance(_context).initSubList();
		}
		else
		{
			return InStaffList.getInstance(_context).initList();
		}
	}

	private ShowStaffListTask _taskInstance;

	public void load(int showType)
	{
		_taskInstance = new ShowStaffListTask(showType);
		_taskInstance.execute();
	}

	public void load(int showType, SysUser selectPatient)
	{
		_taskInstance = new ShowStaffListTask(showType, selectPatient);
		_taskInstance.execute();
	}
}